﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace Allinpay
{
    internal static class ObjectExtensions
    {
        public static string FormatWith(this string format, params object[] args)
        {
            return string.Format(format, args);
        }


        public static string ToStringEx(this object obj)
        {
            return obj == null ? null : obj.ToString();
        }
        public static bool IsNullOrWhiteSpace(this string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }

        public static bool IsNotNullAndWhiteSpace(this string str)
        {
            return !string.IsNullOrWhiteSpace(str);
        }

        public static string ToMD5(this string str, int times)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                for (int i = 0; i < times; i++)
                {
                    var arr = Encoding.UTF8.GetBytes(str);
                    arr = md5.ComputeHash(arr);
                    str = string.Join(string.Empty, arr.Select(p => p.ToString("X2")));
                }
                return str;
            }
        }


        public static string UrlDecode(this string s)
        {
            return HttpUtility.UrlDecode(s);
        }
        public static string UrlEncode(this string s)
        {
            return HttpUtility.UrlEncode(s);
        }


        public static T ToDeserialize<T>(this string str)
        {
            if (!str.IsNullOrWhiteSpace())
            {
                return JsonConvert.DeserializeObject<T>(str);
            }
            return default(T);
        }

        public static string StringJoin<T>(this IEnumerable<T> source, string separator = ",")
        {
            return string.Join(separator, source);
        }

    }
}
